package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author 安贺
 * @createTime 2022年09月01日 11:15:00
 * @description
 */
public class SimpleRedisLock implements ILock {


    private StringRedisTemplate stringRedisTemplate;

    private String name;

    private static final String LOCK_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("/lua/unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(Long timeSec) {
        System.out.println(ID_PREFIX);
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name,
                threadId, timeSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(ifAbsent);
    }

    @Override
    public void unLock() {
        //调用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(LOCK_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());

    }

    //如果发生阻塞，可能由于jvm的full gc的原因，获取和删除时，会发生原子性问题，采用lua脚本确保获取和删除是原子操作
   /* @Override
    public void unLock() {

        String threadId = ID_PREFIX + Thread.currentThread().getId();

        String id = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(LOCK_PREFIX + name);
        }
    }*/
}
